/**
 * 
 */
package com.zaprit.search.support;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Properties;

import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.LBHttpSolrServer;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrResourceLoader;

/**
 * @author Root
 */
public class SolrSupport extends SolrServer
{
	/**
	 * 
	 */
	private static final long	serialVersionUID	= -3077426822983780594L;
	private SolrServer			solrServer			= null;
	private SolrCore			solrCore			= null;
	private String				urls				= null;
	private String				solrDataDir			= null;
	@SuppressWarnings("unused")
	private Properties			properties			= null;

	/**
	 * @param properties
	 */
	public SolrSupport(Properties properties)
	{
		this.properties = properties;
		this.solrDataDir = "data/{scope_id}";
		// list of baseUrls seperated with , and ""
		this.urls = properties.getProperty("solr.urls");
	}

	public NamedList<Object> request(SolrRequest solrRequest) throws SolrServerException, IOException
	{
		return getSolrServer(solrRequest.getParams().get("scopeId")).request(solrRequest);
	}

	/**
	 * @param scopeId
	 * @return SolrServer
	 */
	public SolrServer getSolrServer(String scopeId)
	{
		if (solrServer != null)
		{
			return solrServer;
		}

		synchronized (scopeId)
		{
			if (solrServer != null)
			{
				return solrServer;
			}

			try
			{
				CoreContainer container = new CoreContainer(SolrResourceLoader.locateSolrHome());
				CoreDescriptor descriptor = new CoreDescriptor(container, scopeId, solrDataDir);

				solrCore = container.create(descriptor);
				container.register(scopeId, solrCore, false);
				// SolrServer lbHttpSolrServer = new
				// LBHttpSolrServer("http://host1:8080/solr/","http://host2:8080/solr","http://host3:8080/solr");
				solrServer = new LBHttpSolrServer(urls);
			}
			catch (MalformedURLException e)
			{
				e.printStackTrace();
			}

			return solrServer;
		}
	}

	@Override
	public void shutdown()
	{
		if (solrServer != null)
		{
			solrServer.shutdown();
		}
	}
}
